 <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <style>
        table
        {
           border-collapse: collapse;
           margin-bottom: 10px;
        }
        td{
            border: 1px solid #999;
            padding:10px;
        }
        button
        {
            margin: 2px;
        }
       
    </style>
</head>

<body>
    <div id="app">
    <!-- 设置books存在时展示不存在就展示提示消息 -->
      <template v-if="books.length>0">
        <table>
        <tr><td> </td><td>书籍名称</td><td>出版日期</td><td>价格</td><td>购买数量</td><td>操作</td></tr>
        <tbody>
            <!-- v-for要绑定key -->
            <tr v-for="item,index in books" :key="item.id">
                <td>{{item.id}} </td>
                <td>{{item.name}} </td>
                <td>{{item.date}} </td>
                <td>{{formatPrice(item.price)}} </td>
                <td>
                    <!-- 要给-设置禁用-->
                    <button @click="Sub(index)" :="{disabled:item.count<=1}" >-</button>
                    {{item.count}}
                    <button @click="Add(index)">+</button>
                </td>
                <td><button @click="Delitem">移除</button></td>
            </tr>
        </tbody>
      </table>
    <div>总价：{{formatPrice(TotalPrice)}}</div>
</template>
<template v-else>
   <p>当前购物车为空，请添加书籍</p>
</template>
    </div>
    <script src="./js/books.js"></script>
    <script src="../lib/Vue.js"></script>
    <script>
        const app = Vue.createApp({
            data: function () {
                console.log(books);
               return{
                  books:books,
                  totalPrice:0
               }
            },
            methods: {
                //绑定事件，绑定数量加减按钮
                Sub(index)
                {
                     this.books[index].count--;
                   
                },
                Add(index)
                {
                    this.books[index].count++;
                },
                //绑定移除按钮
                Delitem(index)
                {
                  this.books.splice(index,1);
                },
                //添加人名币符号
                formatPrice(price)
                {
                    return "￥"+price;
                }
            }
            ,
            computed:{
             //计算总价格
               TotalPrice()
               {
                 let totalPrice = 0;
                 totalPrice = this.books.reduce(function(preVal,item){
                    return item.price*item.count+preVal;
                 },0);
                 return totalPrice;
               }
            }
        });
        app.mount("#app");
    </script>
</body>

</html>